const express = require('express');
const path = require('path');
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import App from './routes';
import homeReducer from './store/home';
import routeConfig from './routeConfig';

const app = express();

app.use(express.static(path.resolve(__dirname, 'public')));

app.get('*', async (req, res) => {
  const store = configureStore({
    reducer: {
      home: homeReducer,
    },
  });

  await Promise.all(
    routeConfig.map((item) => {
      if (item.path === req.url && item.component.initProps) {
        return item.component.initProps(store);
      } else {
        return null;
      }
    })
  );

  const preloadedState = store.getState();

  const html = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.url}>
        <App />
      </StaticRouter>
    </Provider>
  );

  res.send(`
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
  </head>
  <body>
      <div id="root">${html}</div>
      <script>
          window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
        </script>
      <script src="/main.client.js"></script>
  </body>
  </html>
  `);
});

app.listen(3000);
